﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace PromoOffersCrawler.Crawler.Managers
{
    public class WebClientCacheEnabled
    {
        public bool EnableCache { get; private set; }

        public ConcurrentDictionary<string, HtmlAnalyzer> RequestCache { get; set; }
        public ConcurrentDictionary<string, string> UrlTexts { get; set; }

        public WebClientCacheEnabled(bool cacheResult = true)
        {
            EnableCache = cacheResult;
            RequestCache = new ConcurrentDictionary<string, HtmlAnalyzer>();
            UrlTexts = new ConcurrentDictionary<string, string>();
        }

        public HtmlAnalyzer GetDownloadStringAsParsedHtml(string url, string urlText)
        {
            if (!EnableCache || !RequestCache.ContainsKey(url))
            {
                return this.DownloadStringAsParsedHtml(url, urlText);
            }

            return RequestCache[url];
        }


        private HtmlAnalyzer DownloadStringAsParsedHtml(string url, string urlText)
        {
            var dataString = DownloadString(url);

            var result = new HtmlAnalyzer(dataString, url);
            UrlTexts[url] = urlText;
            if (EnableCache)
            {
                RequestCache[url] = result;
            }

            return result;
        }

        private string DownloadString(string url)
        {

            var webClient = new WebClient();
            webClient.Encoding = System.Text.Encoding.UTF8;
            return webClient.DownloadString(url);
        }

        internal string GetAnchorText(string p)
        {
            return this.UrlTexts[p];
        }
    }
}
